package net.xxcl.exam.interceptor;

import net.xxcl.exam.mapper.ActionMapper;
import net.xxcl.exam.pojo.Action;
import net.xxcl.exam.pojo.Criteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * User: 夏汛
 * Date: 12-1-18
 * Time: 下午10:17
 */
@Service
public class AuthInterceptor implements HandlerInterceptor{

    @Autowired
    private ActionMapper actionMapper;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
    String requestURI = request.getRequestURI();
    //如果是登录请求不继续验证权限
    if(requestURI.equals("/user/login.do") || requestURI.equals("/student/login.do")){
        return true;
    }
    if(request.getSession().getAttribute("user")==null && request.getSession().getAttribute("student")==null){
        response.setHeader("sessionstatus","timeout");
        return false;
    } else if(request.getSession().getAttribute("student")!=null){
        //因学生能够做的操作不多，且不需要动态分配权限，此处硬编码实现权限控制
        if(requestURI.equals("/paper/getPaperforKs.do")
                || requestURI.equals("/student/getStudentState.do")
                || requestURI.equals("/ks/startKs.do")
                || requestURI.equals("/ks/saveAnswer.do")
                || requestURI.equals("/score/submitPaper.do")
                || requestURI.equals("/ks/uploadResult.do")
                || requestURI.equals("/ks/end.do")
                || requestURI.equals("/ks/downloadFile.do")
                || requestURI.equals("/paper/getPaperforLook.do")){
            return true;
        }
        response.setHeader("sessionstatus","timeout");
        return false;
    } else {
        //管理员或教师
        List<Integer> roles = (List<Integer>)request.getSession().getAttribute("roles");
        Criteria criteria = new Criteria();
        criteria.put("roles",roles);
        criteria.put("action",requestURI);
        List<Action> actions = actionMapper.userAuthUrl(criteria);
        return true;
    }
}

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {

    }
}
